package br.com.verde.exemploteca.concurrency.callable;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class Application {
	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		Thread.sleep(20000);
		System.out.println("Começou!");
		// cria um pool de threads para realizar o cálculo
		ExecutorService executorService = Executors.newCachedThreadPool();

		// separa o cálculo em 4 partes definindo o valor de n inicial e final
		// para cada uma
		Future<Double> part1 = executorService.submit(new CalculatePi(1,
				100000000));
		Future<Double> part2 = executorService.submit(new CalculatePi(
				100000001, 200000000));
		Future<Double> part3 = executorService.submit(new CalculatePi(
				200000001, 300000000));
		Future<Double> part4 = executorService.submit(new CalculatePi(
				300000001, 400000000));

		// junta os valores cálculados das 4 partes e multiplica por 4

		Double result1 = part1.get();
		System.out.println(result1);
		Double result2 = part2.get();
		System.out.println(result2);
		Double result3 = part3.get();
		System.out.println(result3);
		Double result4 = part4.get();
		System.out.println(result4);

		double pi = 4.0 * (result1 + result2 + result3 + result4);

		executorService.shutdown();

		System.out.println("Valor calculado de PI é " + pi);
	}
}
